#!/bin/bash

# 检查参数有效性
if [[ $# -lt 1 ]]; then
    echo "Usage: $0 <file_pattern>" >&2
    exit 1
fi

# 处理每个输入的json文件
for file in "$@"; do
    if [[ ! -f "${file}" ]]; then
        echo "Warning: File '${file}' not found, skipping..." >&2
        continue
    fi

    # 提取关键字段数据,-r:以 raw 模式输出，即不包裹引号
    jq_output=$(
        jq -r --arg filename "${file}" '
            .traceEvents[]
            | select(.name == "__hipPushCallConfiguration" or .name == "__hipPopCallConfiguration")
            | "\(.args.tid) \(.name) \(.args.BeginNs | tonumber) \(.args.EndNs | tonumber)"
        ' "${file}" 2>&1
    )
    jq_status=$?

    # 处理jq解析错误
    if [[ ${jq_status} -ne 0 ]]; then
        {
            echo "[ERROR] Failed to parse ${file}:"
            echo "${jq_output}"
            echo "----------------------------------------"
        } >&2
        continue
    fi

    # 数据处理阶段
    echo "${jq_output}" | awk \
        -v OFS="," \
        -v file="${file}" \
        '
        # 定义数据统计函数
        function calculate_diff(push_end, pop_begin, pid_tid,    _diff) {
            _diff = pop_begin - push_end

            # 记录原始数据（按时间顺序存储）
            data[pid_tid][++counts[pid_tid]] = _diff  # counts从1开始递增

            sums[pid_tid] += _diff

            if (min[pid_tid] == 0 || _diff < min[pid_tid]) {
                min[pid_tid] = _diff
            }

            if (max[pid_tid] == 0 || _diff > max[pid_tid]) {
                second_max[pid_tid] = max[pid_tid]
                max[pid_tid] = _diff
            } else if (_diff > second_max[pid_tid]) {
                second_max[pid_tid] = _diff
            }
        }

        # 计算排除第一个数据后的平均值
        function avg_exclude_first(pid_tid,    sum_excl_first, n) {
            n = counts[pid_tid]
            if (n <= 1) return 0  # 无法排除唯一数据

            sum_excl_first = 0
            for (i = 2; i <= n; i++) {  # 从第二个数据开始
                sum_excl_first += data[pid_tid][i]
            }
            return sum_excl_first / (n - 1)
        }

        # 初始化处理
        BEGIN {
            FS = " "
            printf "%-8s %-10s %-12s %-12s %-12s %-12s %-12s (File: %s)\n",
                "TID", "Count", "Max(ns)", "SecondMax", "Min(ns)", "Avg(ns)", "AvgExclFirst", file
        }

        # 主处理逻辑
        {
            pid_tid = $1
            event_type = $2

            if (event_type == "__hipPushCallConfiguration") {
                push_end = $4
                push[pid_tid] = push_end
            } else if (event_type == "__hipPopCallConfiguration") {
                pop_begin = $3
                if (push[pid_tid] != "") {
                    calculate_diff(push[pid_tid], pop_begin, pid_tid)
                    delete push[pid_tid]
                }
            }
        }

        END {
            # 打印未匹配的Push事件警告(可能是同一组push/pop数据分割在了不同json导致)
            for (pid_tid in push) {
                # printf "WARN: Orphan Push event in TID %s\n", pid_tid > "/dev/stderr"
                printf "WARN: Orphan Push event in TID %s\n", pid_tid > "/dev/stdout"
            }

            # 输出统计结果
            PROCINFO["sorted_in"] = "@ind_num_asc"
            for (pid_tid in counts) {
                avg = counts[pid_tid] > 0 ? sums[pid_tid] / counts[pid_tid] : 0
                avg_excl_first = avg_exclude_first(pid_tid)
                printf "%-8d %-10d %-12d %-12d %-12d %-12.2f %-12.2f\n",
                    pid_tid, counts[pid_tid], max[pid_tid], second_max[pid_tid],
                    min[pid_tid], avg, avg_excl_first
            }
        }
        '
done